import Vue from 'vue'
import Router from 'vue-router'
import Home from './views/Home.vue'

Vue.use(Router)

// 随机生成当前访问者身份，用户，管理员
let flag = Math.random()
if (flag > 0.5) {
  // 假设是管理员
  console.log('我是管理员')
  localStorage.setItem('authList', JSON.stringify(['user', 'admin']))
} else {
  // 假设是用户
  console.log('我是用户')
  localStorage.setItem('authList', JSON.stringify(['user']))
}

const router = new Router({
  routes: [
    {
      path: '/',
      name: 'home',
      component: Home,
      meta: {  // 元信息
        auths: 'user'
      }
    },
    {
      path: '/401',
      name: 'test',
      meta: {
        auths: 'user'
      },
      component: () => import('./views/Test.vue')
    },
    {
      path: '/about',
      name: 'about',
      component: () => import('./views/About.vue'),
      meta: {
        auths: 'user'
      }
    },
    {
      path: '/money',
      name: 'money',
      component: () => import('./views/Money.vue'),
      meta: {
        auths: 'admin'
      }
    }
  ]
})

router.beforeEach((to,from,next)=>{
  var authsList = JSON.parse(localStorage.getItem('authList')) || []

  var hasAuth = function(){
    return authsList.includes(to.meta.auths) 
  }

  if (hasAuth()) {
    next()
  } else {
    next({path: '/401'})
  }
})

export default router